<template>
    <div
      :id="id"
      ref="cesiumContainer"
      :style="{height,width}"
      style="margin: auto;"
    >
    <Statusbar ref="statusBar"></Statusbar>
  </div>
  </template>
  
  <script>
  import 'cesium/Build/Cesium/Widgets/widgets.css'
  import { Cartesian3, Color, GeoJsonDataSource, Ion, JulianDate, Math, Matrix4, Terrain, Viewer} from 'cesium'
  import Statusbar from './statusbar.vue'
  import chainMap from '@/assets/map/chain.topojson'
import scenarioDeduce from '@/scenario/scenarioDeduce'

  
  export default {
    name: 'CesiumMap',
    components:{
      Statusbar
    },
    props: {
      id: {
        type: String,
        default: (() => Math.randomBetween(1,100).toString())()
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '100%'
      }
    },
    data() {
      return {
        viewer: null
      }
    },
    mounted() {
      this.initCesium();

      //所有的操作，都是基于者之后的，要确定 viewer 是已经初始化好了，所以，都要调用此方法来进行viewer的赋值，这个才是其后面所有组件的初始化方法
      for (const  name in this.$refs) {
        //此为监听就位
        console.log(name);
        if(name !== 'cesiumContainer'){
         this.$refs[name].listenerPositon(this.viewer);
        }
      };

      let sd  = scenarioDeduce.init(this.viewer);

      //其他的组件中，还是不能有viewer对象，上面的方法只能做到此页中所有的组件，也许不需要这个方法了
      this.$store.state.curViewer = this.viewer
      this.$store.state.scenarioDeduce = sd;
     
    },
    beforeDestroy() {
      if (this.viewer) {
        this.viewer.destroy()
        this.viewer = null
      }
    },
    methods: {
      initCesium () {
        const el = this.$refs.cesiumContainer

        //开发者默认的ION
       Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZDI2OGQwOC05ODEyLTQ3ZDctODE4YS0wM2JhN2ExNmM3NmIiLCJpZCI6Mjg5Nzk3LCJpYXQiOjE3NDM0ODA5NjZ9.8uaSQlWbJVEte_2arnMD52ccV-a67IEK04gLI-3zG_o';
        this.viewer = new Viewer(el, {
          selectionIndicator: false,
          infoBox: false,
          contextOptions: {
            // 硬件反走样，默认值为 1
            msaaLevel: 8,
            requestWebgl2: true
          },
          terrain:Terrain.fromWorldTerrain(),
          // terrainExaggeration:40,
          animation: true,
          timeline: true, // 底部时间线
          fullscreenButton: false, // 全屏
          vrButton: false, // VR
          sceneModePicker: false, // 选择视角的模式（球体、平铺、斜视平铺）
          baseLayerPicker: false, // 图层选择器（地形影像服务）
          navigationHelpButton: false, // 导航帮助(手势，鼠标)
          geocoder: false, // 位置查找工具
          homeButton: true// 视角返回初始位置
        });

        //设置初始进入经纬度,中国的经纬度
        const lat = 26.724;//24.8851;
        const lon = 113.905;//120.9758;

        //设置初始位置，高度是5000 米高度  5000000
        let homePosition= Cartesian3.fromDegrees(lon,lat,5000000);
   
        //初始的飞入视角
        this.viewer.camera.flyTo({
            destination: homePosition,
            duration:5,
            endTransform:Matrix4.IDENTITY
        });

        this.viewer._cesiumWidget._creditContainer.style.display = "none";

        this.viewer.homeButton.viewModel.command.afterExecute.addEventListener(()=>{
         
          this.viewer.camera.flyTo({
              destination: homePosition,
              duration:5,
              endTransform:Matrix4.IDENTITY
          });
        });

        //时间线的处理
        this.timeHander();

        //加载地图数据
        this.loadDataSource();

      },
      loadDataSource(){
        Math.setRandomNumberSeed(0);

        GeoJsonDataSource.load(chainMap).then(dataSource =>{
          //关键一步，将数据加载到viewer 实例中
          this.viewer.dataSources.add(dataSource);

          const entities = dataSource.entities.values;

          const colorHash = {};
          for (let i = 0; i < entities.length; i++) {
            const entity = entities[i];
            const name = entity.name;
            // console.log(name);
            let color = colorHash[name];
            if(!color){
              color = Color.fromRandom({alpha:0.38});
              colorHash[name] = color;
            }
            entity.polygon.material = color;
            entity.polygon.outline = false;
            entity.polygon.show = true;
            //高度先不设置
           // entity.polygon.extrudedHeight = entity.properties.Population / 50.0; 
          }
        }).catch(err =>{
          console.log(err);
        })
      },
      timeHander(){
        this.viewer.animation.viewModel.dateFormatter=this.localeDateTimeFormatter;
        this.viewer.animation.viewModel.timeFormatter=this.localeTimeFormatter;
        this.viewer.timeline.makeLabel=time => {
          return this.localeDateTimeFormatter(time, null, false);
        }
      },
      //日期时间同时转换
      localeDateTimeFormatter(datetime,viewModel,ignoredate){
          let juLianDt=new JulianDate();
          JulianDate.addHours(datetime,8,juLianDt);
          let greDt=JulianDate.toGregorianDate(juLianDt);
          let objDt;
          if(ignoredate){
            objDt="";
          }else{
            objDt=new Date(greDt.year,greDt.month-1,greDt.day);
            objDt=greDt.year +"年"+objDt.toLocaleString("zh-cn",{month:"short"})+greDt.day+"日";
            if(viewModel || greDt.hour+greDt.minute ===0){
              return objDt;
            }else if(!viewModel){
              return objDt+" "+this.formatNum10(greDt.hour)+":"+this.formatNum10(greDt.minute)+":"+this.formatNum10(greDt.second);
            }
            objDt+=""
          }
          return objDt+" "+this.formatNum10(greDt.hour)+":"+this.formatNum10(greDt.minute)+":"+this.formatNum10(greDt.second);
        },
        localeTimeFormatter(time,viewModel){
          return this.localeDateTimeFormatter(time,viewModel,true);
        },
        //判断是否大于10，是就用，不是就加 0
        formatNum10(num){
          if(num == undefined){
            return "";
          }
          return num > 9?num : "0"+num;
        }
    }
  }
  </script>
 